package servlet;

import com.mysql.jdbc.PreparedStatement;
import model.Commodity;
import util.DBHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/saveCommodityDelete.do")
public class SaveCommodityDeleteServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Commodity> commodities = new ArrayList<>();
        int CID = Integer.parseInt(request.getParameter("cid"));
        // 一段sql语句
        Connection conn = null;
        try { // 创建PreparedStatement
            conn = DBHelper.getConnection();
            String sql = "delete from commodity where cid=?";
            PreparedStatement pstat = (PreparedStatement) conn.prepareStatement(sql);
            // PreparedStatement赋值
            pstat.setInt(1, CID);
            pstat.execute();
            String sql1 = "SELECT cid,number,price,c_name,photo FROM commodity";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql1);
            while (rs.next()){

                Commodity commodity = new Commodity(rs.getInt("cid"),
                        rs.getInt("number"),
                        rs.getFloat("price"),
                        rs.getString("c_name"),
                        rs.getString("photo"));
                commodities.add(commodity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.getSession().setAttribute("commodities",commodities);
        request.getRequestDispatcher("AdminCommodity.jsp").forward(request,response);
    }
}